<template>
    <div class="live-standard">
    <nav-header>
        <li>
            <router-link to="/resources/live/live-broadcast">预约直播</router-link>
        <li>
        <li class="gap">&gt;</li><li v-text="navTxtFlag ? '编辑评估标准' : '评课标准'"></li> 
    </nav-header>
        <div class="standard-box">
            <el-form :model="ruleForm" :rules="rules" ref="ruleFF" label-width="100px" class="demo-ruleForm">
                <el-form-item 
                    label="标准名称" 
                    prop="name" 
                >
                    <el-input v-model="ruleForm.name" maxlength="20" placeholder="最多可输入20个字"></el-input>
                </el-form-item>
                <el-form-item label="适用学科" prop="subject_id">
                    <el-select v-model="ruleForm.subject_id" style="width: 240px" filterable placeholder="请选择学科">
                        <el-option
                            v-for="item in orgSubjectKind"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
                <div class="total-score">
                    <h4>标准详情</h4>
                    <div class="score-btn score-lx">
                        <el-button type="text" @click="Addentry()">添加打分项</el-button>
                    </div>
                    <div class="score-l1" v-for="(item, index) in ruleForm.item_data" :key="index">
                        <el-form :model="item" :ref="'ruleForm' + index" label-width="100px" class="demo-ruleForm clear">
                                <el-col :span="15">
                                    <el-form-item label="打分项" prop="name" :rules="[
                                        { validator: checkSpace,required: true}
                                    ]">
                                        <el-input v-model="item.name" maxlength=10  placeholder="最多可以输入10个字"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="7">
                                    <el-form-item label="设置分数" v-show="item.children.length === 0" prop="score" :rules="[
                                        {validator: checkScore, trigger: 'blur',required: true}
                                        ]">
                                        <el-input-number v-model="item.score" @blur="calTotalScore" :controls="false" :min="0" :max="100" label="设置分数" :disabled="item.children.length > 0"></el-input-number>
                                    </el-form-item>
                                </el-col>
                                <el-col class="line" :span="item.children.length > 0 ? 9 : 2">
                                    <i class="el-icon-close" @click="removerEntry(index)"></i>
                                </el-col>
                        </el-form>
                        <div class="score-l2" v-for="(item2, index2) in item.children" :key="index2">
                            <el-form :model="item2" :ref="'ruleForm-item' + index2" label-width="100px" class="demo-ruleForm clear">
                                    <el-col :span="15" class="form-item-col">
                                        <el-form-item label="细分项" prop="name" :rules="[
                                            { validator: checkSpace,required: true}
                                        ]">
                                            <el-input 
                                            v-model="item2.name"
                                            type="textarea"
                                            :rows="4" resize="none"
                                            maxlength=200
                                            max=100
                                            placeholder="你最多可以输入200个字"></el-input>
                                            
                                        </el-form-item>
                                        <span class="nubxx"><i>{{item2.name.length}}</i>/200</span>
                                    </el-col>
                                    <el-col :span="7">
                                        <el-form-item label="设置分数" prop="score" :rules="[
                                            {validator: checkScore, trigger: 'blur',required: true}
                                        ]">
                        <el-input-number v-model="item2.score" @blur="calTotalScore" :controls="false" :min="0" :max="100" label="设置分数"></el-input-number>
                                        </el-form-item>
                                    </el-col>
                                    <el-col class="line" :span="2">
                                        <i class="el-icon-close" @click="removerEntryChild(index ,index2)"></i>
                                    </el-col>
                            </el-form>
                        </div>
                        <div class="score-btn">
                            <el-button type="text" @click="AddentryChild(index)">添加细分项</el-button>
                        </div>
                    </div>
                </div>
                <div class="buttonCSS">
                    <el-button @click="$router.push('/resources/live/live-broadcast')" type="primary" plain>取消</el-button>
                    <el-button type="primary" @click="submitForm('ruleFF')" v-text="navTxtFlag ? '保存' : '确定'"></el-button>
                </div>
        </div>
    </div>
</template>

<script>
    export default {
    data() {
        return {
        orgSubjectKind: [], //学科
        listDatas: [],
        navTxtFlag: null,
        dataItem: [],
        ruleForm: {
            id: 0,
            userid: JSON.parse(sessionStorage.getItem('user_info_str')).id,
            status: 1,
            authority: 1,
            name: "",
            subject_id: "",
            classify_id: "",
            item_data: [
            {
                name: "",
                score: 0,
                children: [{ name: "", score: 0, id: 0 }]
            }
            ]
        },
        rules: {
            name: [
            { validator: this.checkSpace, required: true },
            { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
            ],
            classify_id: [
                { required: true, message: "请选择分类", trigger: "change" }
            ],
            subject_id: [
                { required: true, message: "请选择分类", trigger: "change" }
            ]
        },
        subjectParam: {
            //获取科目,版本，参数
        },
        };
    },
    created() {
        if (
        !is_empty(this.$route.params.id) &&
        parseInt(this.$route.params.id) > 0
        ) {
        this.ruleForm.id = this.$route.params.id;
        this.getInfo();
        }
        if( !is_empty( this.$route.params.id ) ){
            this.navTxtFlag = this.$route.params.id ;
        }
        this.getSubjectKind()
        this.getList();
    },
    methods: {
        getList(){
            let params = {
                status: 0,
                classify_id: '',
                keyword: '',
                page_index:1,
                page_size:10,
            }
            let success = (data=>{
                // console.log(data.data.data)
                this.listDatas = data.data.data
            })
            //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
            this.$ajax.get('api/network/eva_standard',{params, func:{success:success}})
        },
        //获取评课标准分类
        getSubjectKind() {
            let success = data => {
                this.orgSubjectKind = data.data;
            };
            this.$ajax.get("api/newlevel/platform_subject", {params: this.subjectParam,func: { success: success }})
        },

        getInfo() {
            console.log(this.ruleForm.id)
        let success = data => {
            console.log(data, 123)
            this.ruleForm.name = data.data.name;
            this.ruleForm.classify_id = data.data.classify_id;
            this.ruleForm.subject_id = data.data.subject_id;
            if (
            !is_empty(data.data.standard_item) &&
            data.data.standard_item.length > 0
            ) {
            this.ruleForm.item_data = [];
            for (var i = 0; i < data.data.standard_item.length; i++) {
                var item_data = { children: [] };
                item_data.id = data.data.standard_item[i].id;
                item_data.name = data.data.standard_item[i].name;
                item_data.pid = data.data.standard_item[i].pid;
                item_data.score = data.data.standard_item[i].score;
                if (
                !is_empty(data.data.standard_item[i].child) &&
                data.data.standard_item[i].child.length > 0
                ) {
                for (
                    var j = 0;
                    j < data.data.standard_item[i].child.length;
                    j++
                ) {
                    item_data.children.push({
                    id: data.data.standard_item[i].child[j].id,
                    name: data.data.standard_item[i].child[j].name,
                    pid: data.data.standard_item[i].child[j].pid,
                    score: data.data.standard_item[i].child[j].score
                    });
                }
                } else {
                item_data.children = [];
                }
                this.ruleForm.item_data.push(item_data);
            }
            }
        };
        this.$ajax.get("api/network/standard_detail", {
            params: { id: this.ruleForm.id },
            func: { success: success }
        });
        },
        calTotalScore() {
        for (var i = this.ruleForm.item_data.length - 1; i >= 0; i--) {
            if (this.ruleForm.item_data[i].children.length > 0) {
            this.ruleForm.item_data[i].score = 0;
            var score_column = getOneColumn(
                this.ruleForm.item_data[i].children,
                "score"
            );
            for (var j = score_column.length - 1; j >= 0; j--) {
                if (score_column[j] == undefined) {
                score_column[j] = 0;
                }
                this.ruleForm.item_data[i].score += parseInt(score_column[j]);
            }
            } else {

            }
        }
        },
        saveStandard() {
            let success = data => {
                this.$message.success(data.msg);
                this.$router.push("/teaching/research/evaluation-criteria");
            };
            //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
            if (!is_empty(this.ruleForm.id) && parseInt(this.ruleForm.id) > 0) {
                this.$ajax.put("api/network/manage_standar", this.ruleForm, {func: { success: success }});
            } else {
                
                this.$ajax.post("api/network/manage_standar", this.ruleForm, {func: { success: success }});
            }
        },
        //添加项目
        Addentry() {
        this.ruleForm.item_data.push({
            name: "",
            score: 0,
            children: [{ name: "", score: 0, id: 0 }]
        });
        },
        //添加子项目
        AddentryChild(index) {
        this.ruleForm.item_data[index].children.push({ name: "", score: 0 });
        },
        //删除子项目
        removerEntry(index) {
            this.ruleForm.item_data.splice(index, 1);
            this.calTotalScore();
        },
        //删除子项目
        removerEntryChild(index, index2) {
            this.ruleForm.item_data[index].children.splice(index2, 1);
            this.calTotalScore();
        },
        submitForm(formName) {
        this.$refs[formName].validate(valid => {
            if(valid) {
            this.formValid("verify");
            }
        });
        },
        formValid(flag) {

        /*验证组件中所有的表单*/
        let forms = this.$refs;
        let endValids = [];
        console.log(forms,'666')
        for (let form in forms) {
            if (form.indexOf("ruleForm") > -1) {
                if (forms[form].length > 0) {
                    forms[form].forEach(element => {
                    if (flag === "verify") {
                        element.validate(valid => {
                            console.log(endValids,valid)
                        endValids.push(valid);
                        });
                    }
                    if (flag === "reset") {
                        element.resetFields();
                    }
                    });
                }
            }
        }
        if (endValids.indexOf(false) < 0) {
            console.log(22)
            this.saveStandard();
        }
        },
        resetForm(formName) {
        if ( !is_empty( this.navTxtFlag ) ) {
            this.getInfo();
            return;
        }else{
            this.ruleForm = {
                id: 0,
                name: "",
                classify_id: "",
                item_data: [
                    {
                    name: "",
                    score: 0,
                    children: [{ name: "", score: 0, id: 0 }]
                    }
                ]
            }
        }
        this.$refs[formName].clearValidate();
        },
        checkSpace(rule, value, callback) {
        let trim = value.trim();
        if (!trim) {
            callback(new Error("请输入内容"));
        } else {
            callback();
        }
        },
        checkSpace(rule, value, callback) {
        let trim = value.trim();
        if (!trim) {
            callback(new Error("请输入内容"));
        } else {
            callback();
        }
        },
        checkAllScore(rule, value, callback) {
        if (value < 3 || value > 100) {
            callback(new Error("标准总分须是3-100的数字值"));
        } else {
            callback();
        }
        },
        checkScore(rule, value, callback) {
        if (value == undefined) {
            value = 0;
        }
        if (value < 1 || value > 100) {
            callback(new Error("须是1-100的数字值"));
        } else {
            callback();
        }
        }
    }
    };
</script>

<style lang="scss">
.live-standard {
    .standard-box {
        margin-top: 30px;
        max-width: 800px;
    }
    .score-l1 {
        margin-bottom: 20px;
        background: #f5f5f5;
        padding: 20px;
        .line {
        text-align: right;
        font-size: 18px;
        }
        > .el-form-item {
        margin-bottom: 0;
        }
        .nubxx {
            position: absolute;
            right: 12px;
            bottom: 1px;
            padding: 3px 5px;
            font-size: 12px;
            color: #999;
            background: #fff;

            i {
                color: #333;
            }
        }
    }
    .score-l2 {
        margin-bottom: 20px;
        > .el-form-item {
        margin-bottom: 0;
        }
    }

    .score-btn {
        .el-icon-plus {
        padding: 10px;
        background: #deefff;
        border-radius: 3px;
        color: #a0c1e1;
        cursor: pointer;
        -webkit-transition: 0.3s;
        transition: 0.3s;
        margin-right: 10px;
        &:hover {
            color: #fff;
            background-color: #409eff;
        }
        }
    }

    .score-lx {
        padding-left: 20px;
        margin-bottom: 40px;
    }
    }
    .form-item-col {
    position: relative;
    .el-form-item {
        margin-bottom: 0;
    }
}
</style>